package com.africanmoviesmobile.ui;

import java.io.IOException;

import org.pixmob.httpclient.HttpClientException;

import android.annotation.TargetApi;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.africanmoviesmobile.R;
import com.africanmoviesmobile.util.bitmap.ImageCache.ImageCacheParams;
import com.africanmoviesmobile.util.bitmap.ImageFetcher;
import com.africanmoviesmobile.util.bitmap.Utils;
import com.africanmoviesmobile.webservice.AmmWebService;
import com.africanmoviesmobile.webservice.BasicAsyncCallback;
import com.africanmoviesmobile.webservice.WebServiceException;
import com.africanmoviesmobile.webservice.inf.Celeb;
import com.africanmoviesmobile.webservice.inf.Filmography;
import com.africanmoviesmobile.webservice.inf.Photo;
import com.africanmoviesmobile.webservice.inf.WebserviceObject;
import com.devsmart.android.ui.HorizontalListView;


public class CelebDetailActivity extends BaseActivity {

	public static final String EXTRA_CELEB_ID = "celeb_id";
	
	private LayoutInflater mLayoutInflater;
	private LinearLayout mCelebFilmographyWrapper;
	private LinearLayout mCelebFilmographyListWrapper;
	
	ImageFetcher mCelebPhotoDetailImageFetcher;
	ImageFetcher mPagerThumbnailImageFetcher;
	ImageFetcher mThumbnailImageFetcher;
	
	AmmWebService mAmmWebService;
	Celeb mCelebInfo = null;
	
	private String[] mCelebPhotos;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	
		setContentView(R.layout.celeb_detail_activity);
		
		mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		mCelebFilmographyWrapper = (LinearLayout) findViewById(R.id.celeb_filmography_wrapper);
		mCelebFilmographyListWrapper = (LinearLayout) findViewById(R.id.celeb_filmography_list_wrapper);
		
		int celebPhotoDetailWidth = getResources().getDimensionPixelSize(R.dimen.celeb_photo_detail_width);
		int celebPhotoDetailHeight = getResources().getDimensionPixelSize(R.dimen.celeb_photo_detail_height);
		mCelebPhotoDetailImageFetcher = new ImageFetcher(this, celebPhotoDetailWidth, celebPhotoDetailHeight);
		mCelebPhotoDetailImageFetcher.setLoadingImage(R.drawable.empty_photo);
		mCelebPhotoDetailImageFetcher.addImageCache(getSupportFragmentManager(), new ImageCacheParams(this, CACHE_DIR_FULL));
		
		int pagerThumbnailWidth = getResources().getDimensionPixelSize(R.dimen.pager_thumbnail_width);
		int pagerThumbnailHeight = getResources().getDimensionPixelSize(R.dimen.pager_thumbnail_height);
		mPagerThumbnailImageFetcher = new ImageFetcher(this, pagerThumbnailWidth, pagerThumbnailHeight);
		mPagerThumbnailImageFetcher.setLoadingImage(R.drawable.empty_photo);
		mPagerThumbnailImageFetcher.addImageCache(getSupportFragmentManager(), new ImageCacheParams(this, CACHE_DIR_PAGER_THUMBNAIL));
		
		int thumbnailWidth = getResources().getDimensionPixelSize(R.dimen.thumbnail_width);
		int thumbnailHeight = getResources().getDimensionPixelSize(R.dimen.thumbnail_height);
		mThumbnailImageFetcher = new ImageFetcher(this, thumbnailWidth, thumbnailHeight);
		mThumbnailImageFetcher.setLoadingImage(R.drawable.empty_photo);
		mThumbnailImageFetcher.addImageCache(getSupportFragmentManager(), new ImageCacheParams(this, CACHE_DIR_THUMBNAIL));
		
		mAmmWebService = AmmWebService.getInstance(this);
		
		final int celebId = getIntent().getIntExtra(EXTRA_CELEB_ID, 0);

		mAmmWebService.getCeleb(celebId, new BasicAsyncCallback() {

			public void onComplete(final WebserviceObject[] result, final Object state) {

				Celeb celebInfo = (Celeb) result[0];		

				if ((celebInfo != null)) {
					
					mCelebInfo = celebInfo;
					
					runOnUiThread(new Runnable() {public void run() {  
						
						LinearLayout loadingProgress = (LinearLayout) findViewById(R.id.loading_progress);
						LinearLayout container = (LinearLayout) findViewById(R.id.container);
						
						ImageView celebDefaultPhoto = (ImageView) findViewById(R.id.celeb_default_photo);
						TextView celebName = (TextView) findViewById(R.id.celeb_name);
						TextView celebBirthName = (TextView) findViewById(R.id.celeb_birth_name);
						TextView celebBirthDate = (TextView) findViewById(R.id.celeb_birth_date);
						TextView celebBirthPlace = (TextView) findViewById(R.id.celeb_birth_place);
						TextView celebBiography = (TextView) findViewById(R.id.celeb_biography);
						
						mCelebPhotoDetailImageFetcher.loadImage(mCelebInfo.getDefaultPhoto(), celebDefaultPhoto);
						
						celebName.setText(mCelebInfo.getName());
						celebBirthName.setText(mCelebInfo.getBirthName());
						celebBirthDate.setText(mCelebInfo.getDateOfBirth());
						celebBirthPlace.setText(mCelebInfo.getPlaceOfBirth() + ", " + mCelebInfo.getCountryOfBirth());
						celebBiography.setText(mCelebInfo.getBiography());
						
						loadingProgress.setVisibility(View.GONE);
						container.setVisibility(View.VISIBLE);	
						
					}});
													
					Photo[] celebPhotos = null;
					
					try {
						celebPhotos = (Photo[]) mCelebInfo.getPhotos();
					} catch (HttpClientException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} catch (WebServiceException e) {
						e.printStackTrace();
					}
					
					if ((celebPhotos != null) && (celebPhotos.length > 0)) {
						
						mCelebPhotos = new String[celebPhotos.length];
						
						for (int i = 0; i < celebPhotos.length; i++) {
			        		Photo photo = (Photo) celebPhotos[i];
			        		mCelebPhotos[i] = photo.getPhoto();
			        	}
						
						runOnUiThread(new Runnable() {public void run() { 
							
							LinearLayout celebPhotosWrapper = (LinearLayout) findViewById(R.id.celeb_photos_wrapper);
							celebPhotosWrapper.setVisibility(View.VISIBLE);
															
							HorizontalListView celebPhotosListview = (HorizontalListView) findViewById(R.id.celeb_photos_listview);
							celebPhotosListview.setAdapter(new CelebPhotoListAdapter());
							
							celebPhotosListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
								@TargetApi(16)
								public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
									final Intent intent = new Intent(CelebDetailActivity.this, ImageDetailActivity.class);
									intent.putExtra(ImageDetailActivity.EXTRA_IMAGE, (int) id);
									intent.putExtra(ImageDetailActivity.EXTRA_IMAGES, (String[]) mCelebPhotos);
							        if (Utils.hasJellyBean()) {
							            ActivityOptions options = ActivityOptions.makeScaleUpAnimation(view, 0, 0, view.getWidth(), view.getHeight());
							            startActivity(intent, options.toBundle());
							        } else {
							            startActivity(intent);
							        }
								}
							});
							
						}});
																						
					}
					
					Filmography[] celebFilmographies = null;
					
					try {
						celebFilmographies = (Filmography[]) mCelebInfo.getFilmographies();
					} catch (HttpClientException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} catch (WebServiceException e) {
						e.printStackTrace();
					}
					
					if ((celebFilmographies != null) && (celebFilmographies.length > 0)) {
						
						runOnUiThread(new Runnable() {public void run() { mCelebFilmographyWrapper.setVisibility(View.VISIBLE); }});
						
						final int numDefaultFilmography = 4;
						
						final int countDefaultFilmography = celebFilmographies.length > numDefaultFilmography ? numDefaultFilmography : celebFilmographies.length;
						
						for (int i = 0; i < countDefaultFilmography; i++) {
							
			        		final Filmography filmography = (Filmography) celebFilmographies[i];
			        		
			        		runOnUiThread(new Runnable() {public void run() { 
								
			        			View celebFilmographyRow = mLayoutInflater.inflate(R.layout.celeb_filmography_listview_row, null, false);
				            	
				            	TextView movieTitle = (TextView) celebFilmographyRow.findViewById(R.id.movie_title);
				            	movieTitle.setText(filmography.getMovieTitle());
				            	
				            	TextView movieRoles = (TextView) celebFilmographyRow.findViewById(R.id.movie_roles);
				            	movieRoles.setText(filmography.getRoles());
				            	
				            	ImageView movieCover = (ImageView) celebFilmographyRow.findViewById(R.id.movie_cover);
				            	mThumbnailImageFetcher.loadImage(filmography.getMovieCover(), movieCover);
				        		
				            	celebFilmographyRow.setOnClickListener(new View.OnClickListener() {
									public void onClick(View view) {
										final Intent intent = new Intent(CelebDetailActivity.this, MovieDetailActivity.class);
							    		intent.putExtra(MovieDetailActivity.EXTRA_MOVIE_ID, (int) filmography.getMovieId());
							            startActivity(intent);
									}
								});
				            	
				            	mCelebFilmographyListWrapper.addView(celebFilmographyRow);
								
							}});
			        	}
						
						if(celebFilmographies.length > numDefaultFilmography){
							
							runOnUiThread(new Runnable() {public void run() { 
								
								View simpleListRow1 = mLayoutInflater.inflate(R.layout.simple_list_row_1, null, false);
				            	TextView caption = (TextView) simpleListRow1.findViewById(R.id.caption);
				            	caption.setText("All Filmography");
				            	simpleListRow1.setOnClickListener(new View.OnClickListener() {
									public void onClick(View view) {
										final Intent intent = new Intent(CelebDetailActivity.this, CelebFilmographyListActivity.class);
										intent.putExtra(CelebFilmographyListActivity.EXTRA_CELEB_ID, (int) mCelebInfo.getId());
										intent.putExtra(CelebFilmographyListActivity.EXTRA_CELEB_NAME, (String) mCelebInfo.getName());
								        startActivity(intent);
									}
								});
				            	
				            	mCelebFilmographyWrapper.addView(simpleListRow1);
								
							}});
						}
														
					}
					
				}
				
			}

			public void onHttpClientException(final HttpClientException e, final Object state) {
				Log.w("AMM HttpClientException:", e.getMessage());
			}
			
			public void onIOException(final IOException e, final Object state) {
				Log.w("AMM IOException:", e.getMessage());
			}

			public void onWebServiceException(final WebServiceException e, final Object state) {
				Log.w("AMM WebServiceException:", e.getMessage());
			}

		}, null);
		
	}
	
	@Override
    public void onResume() {
        super.onResume();
        
        mPagerThumbnailImageFetcher.setExitTasksEarly(false);
        
        mCelebPhotoDetailImageFetcher.setExitTasksEarly(false);
        
        mThumbnailImageFetcher.setExitTasksEarly(false);
    }

    @Override
    public void onPause() {
        super.onPause();
        
        mPagerThumbnailImageFetcher.setPauseWork(false);
        mPagerThumbnailImageFetcher.setExitTasksEarly(true);
        mPagerThumbnailImageFetcher.flushCache();
        
        mCelebPhotoDetailImageFetcher.setPauseWork(false);
        mCelebPhotoDetailImageFetcher.setExitTasksEarly(true);
        mCelebPhotoDetailImageFetcher.flushCache();
        
        mThumbnailImageFetcher.setPauseWork(false);
        mThumbnailImageFetcher.setExitTasksEarly(true);
        mThumbnailImageFetcher.flushCache();        
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        
        mPagerThumbnailImageFetcher.closeCache();
        
        mCelebPhotoDetailImageFetcher.closeCache();
        
        mThumbnailImageFetcher.closeCache();
    }
    
	public class CelebPhotoListAdapter extends BaseAdapter {
		        
		private class ViewHolder {
		    public ImageView mCelebPhoto;
		}
		
        public CelebPhotoListAdapter() {
        }

        public int getCount() {
            return mCelebPhotos.length;
        }

         public Object getItem(int position) {
            return position;
        }

         public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
      
        	ViewHolder holder;
        	
        	View celebPhotoRow = convertView;
        	
        	if (celebPhotoRow == null) {
        		
        		celebPhotoRow = mLayoutInflater.inflate(R.layout.celeb_photo_listview_row, parent, false);
        		
        		holder  = new ViewHolder();
        		holder.mCelebPhoto = (ImageView) celebPhotoRow.findViewById(R.id.celeb_photo);
        		
        		celebPhotoRow.setTag(holder);
        		
        	}else{
        		holder = (ViewHolder) celebPhotoRow.getTag();
        	}

        	mPagerThumbnailImageFetcher.loadImage(mCelebPhotos[position], holder.mCelebPhoto);
        	
            return celebPhotoRow;
        }
        
    }
	
}
